package com.eyas.business.service.userinfo;

import com.eyas.business.config.webmvc.UserStr;
import com.eyas.business.config.webmvc.exception.custom.uncheck.EyasBusinessException;
import com.eyas.business.config.webmvc.interceptor.LoginInterceptor;
import com.eyas.business.model.jdbcEntity.table.ChildrenInfo;
import com.eyas.business.model.jdbcEntity.table.UserAndClass;
import com.eyas.business.model.jdbcEntity.table.UserInfo;
import com.eyas.business.model.jpa.AdminInfo;
import com.eyas.business.model.pojo.userinfo.QueryPageParmDTO;
import com.eyas.business.model.pojo.userinfo.QueryPageResultDTO;
import com.eyas.business.model.jdbcEntity.table.UserAndRole;
import static com.eyas.core.jdbc.utils.CommonJdbcUtils.*;

import com.eyas.business.model.pojo.webchat.UserRegisterDTO;
import com.eyas.core.model.page.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Auther: 王龙龙
 * @Date: 2019/3/2 15:49
 * @Description:
 */
@Service
@Transactional
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserStr userStr;

    @Override
    public PageResult<QueryPageResultDTO> queryUserInfo(QueryPageParmDTO queryPageParmDTO, int page, int limit) {
        StringBuffer sb = new StringBuffer("");
        List list = new ArrayList<Object>();
        sb.append(" select a.*,case when a.sex='1' then '男' else '女' end as sexname,case when a.validflag='1' then '有效' else '无效' end as validflagtext, " +
                " b.username as addusername,c.username as updateusername from userinfo a left join admininfo b ")
                .append(" on a.addid=b.adminnid and b.validflag='1' ")
                .append(" left join admininfo c ")
                .append(" on a.updateid=c.adminnid and c.validflag='1' ")
                .append(" where 1=1 ");
        if(StringUtils.hasText(queryPageParmDTO.getOpenid())) {
            sb.append(" and a.openid= ? ");
            list.add(queryPageParmDTO.getOpenid());
        }

        if(StringUtils.hasText(queryPageParmDTO.getTelephone())) {
            sb.append(" and a.telephone= ? ");
            list.add(queryPageParmDTO.getTelephone());
        }

        if(StringUtils.hasText(queryPageParmDTO.getUsername())) {
            sb.append(" and a.username like ? ");
            list.add("%"+queryPageParmDTO.getUsername()+"%");
        }
        if(StringUtils.hasText(queryPageParmDTO.getValidflag())) {
            sb.append(" and a.validflag = ? ");
            list.add(queryPageParmDTO.getValidflag());
        }
        if(queryPageParmDTO.getStarttime()!=null) {
            sb.append(" and a.addtime >= ? ");
            list.add(queryPageParmDTO.getStarttime());
        }
        if(queryPageParmDTO.getEndtime()!=null) {
            sb.append(" and a.addtime <= ? ");
            list.add(queryPageParmDTO.getEndtime());
        }
        if(queryPageParmDTO.getAdminnid()!=null&&queryPageParmDTO.getAdminnid()!=0) {
            sb.append(" and a.addid = ? ");
            list.add(queryPageParmDTO.getAdminnid());
        }

        PageResult<QueryPageResultDTO> pageResult = commonJdbcUtils.queryForPage(sb.toString(),QueryPageResultDTO.class,page,limit,list);
        return pageResult;
    }

    @Override
    public void changeValidflag(int userid) {
        UserInfo userInfo = commonJdbcUtils.queryObject("select * from userinfo where userid=?",UserInfo.class,userid);
        if(userInfo==null)
            throw new EyasBusinessException("数据缺失，请刷新页面重试");
        if(userInfo.getValidflag().equals("1")) {
            userInfo.setValidflag("0");
        }else {
            int count =0;// commonJdbcUtils.queryObject("select count(1) from userinfo where loginname=? and validflag='1'",Integer.class,userInfo.getLoginname());
            if(count>=1)
                throw new EyasBusinessException("该登录账号已存在有效的数据，无法置为有效");
            userInfo.setValidflag("1");
        }
        commonJdbcUtils.update(userInfo);
    }

    @Override
    public UserInfo getUserInfoById(int userid) {
        QueryPageResultDTO userInfo = commonJdbcUtils.queryObject("select a.* from userinfo a  " +
                " where a.userid=?",QueryPageResultDTO.class,userid);
        return userInfo;
    }

    @Override
    public void saveUserInfo(QueryPageParmDTO userInfo, HttpSession session) {
    	AdminInfo adminInfo = (AdminInfo)session.getAttribute(LoginInterceptor.LONGIN_SESSION_NAME);
        if(userInfo.getUserid()!=null&&userInfo.getUserid()>0) { //update
            int count = commonJdbcUtils.queryObject("select count(1) from userinfo where openid=? and validflag='1' and userid<>?",
                    Integer.class,userInfo.getOpenid(),userInfo.getUserid());
            if(count>=1)
                throw new EyasBusinessException("该登录账号已存在有效的数据，");
            UserInfo userInfo1 = commonJdbcUtils.queryObject("select * from userinfo where userid=?",UserInfo.class,userInfo.getUserid());
            if(userInfo.getSex()!=null)
                userInfo1.setSex(userInfo.getSex());
            //排除sex和validflag、addtime，其他的字段进行更新
            BeanUtils.copyProperties(userInfo,userInfo1,"openid","sex","restclass","totleclass","totleamount","rechargenum",
                    "validflag","addtime","tiyannums","tiyansums","userstr");
            userInfo1.setAddid(userInfo.getAddid());
            userInfo1.setUpdateid(adminInfo.getAdminnid());
            userInfo1.setUpdatetime(new Date());
            commonJdbcUtils.update(userInfo1);

            

        }else {// insert
            int count = commonJdbcUtils.queryObject("select count(1) from userinfo where openid=? and validflag='1'",Integer.class,userInfo.getOpenid());
            if(count>=1)
                throw new EyasBusinessException("该登录账号已存在有效的数据，");
            UserInfo userInfo1 = new UserInfo();
            //排除sex和validflag、addid、addtime，其他的字段进行更新
            BeanUtils.copyProperties(userInfo,userInfo1,"sex","validflag","addid","addtime","istiyan","tiyannums","tiyansums","userstr");
            if(userInfo.getSex()==null)
                userInfo1.setSex(1);
            else
                userInfo1.setSex(userInfo.getSex());
            userInfo1.setRestclass(0);
            userInfo1.setTotleclass(0);
            userInfo1.setTotleamount(0);
            userInfo1.setRechargenum(0);
            userInfo1.setValidflag("1");
            userInfo1.setTiyannums(0);
            userInfo1.setTiyansums(0);
            userInfo1.setAddtime(new Date());

            String userstr_no = commonJdbcUtils.queryObject("select nextval(?)",Integer.class,userStr.getSeqname())+"";
            String userstr = userStr.getSeqname();
            for(int i=0;i<5-userstr_no.length();i++) {
                userstr += "0";
            }
            userstr += userstr_no;
            userInfo1.setUserstr(userstr);

            if(adminInfo!=null){
            	userInfo1.setAddid(adminInfo.getAdminnid());
            }
            commonJdbcUtils.insert(userInfo1);
            
        }
    }
    @Override
    public UserInfo getUserInfoByOpenid(String openid) {
        QueryPageResultDTO userInfo = commonJdbcUtils.queryObject("select a.* from userinfo a  " +
                " where a.openid=?",QueryPageResultDTO.class,openid);
        return userInfo;
    }

    @Override
    public PageResult<ChildrenInfo> queryChildrenInfoByUser(Integer userid, int page, int limit) {
        return commonJdbcUtils.queryForPage("select cid,userid,cname,birthday,case when csex='1' then '男' else '女' end as csex" +
                " from childreninfo where userid=? order by cid",ChildrenInfo.class,page,limit,userid);
    }

    @Override
    public ChildrenInfo getChildInfoByCid(Integer cid) {
        return commonJdbcUtils.queryObject("select * from childreninfo where cid=?",ChildrenInfo.class,cid);
    }

    @Override
    public void saveChildrenInfo(ChildrenInfo childrenInfo) {
        if(childrenInfo.getCid()==null||childrenInfo.getCid()==0) {//insert
            if(!StringUtils.hasText(childrenInfo.getCsex())) {
                childrenInfo.setCsex("1");
            }
            commonJdbcUtils.insert(childrenInfo);
        }else {//update
            ChildrenInfo childrenInfo1 = commonJdbcUtils.queryObject("select * from childreninfo where cid=?",ChildrenInfo.class,childrenInfo.getCid());
            BeanUtils.copyProperties(childrenInfo,childrenInfo1,"csex");
            if(StringUtils.hasText(childrenInfo.getCsex())) {
                childrenInfo1.setCsex(childrenInfo.getCsex());
            }
            commonJdbcUtils.update(childrenInfo1);
        }
    }

    @Override
    public List<ChildrenInfo> queryChildrenInfoByUser(Integer userid) {
        return commonJdbcUtils.queryList("select * from childreninfo where userid=? order by cid",ChildrenInfo.class,userid);
    }

    @Override
    public void saveUserInfoPublic(UserRegisterDTO dto, HttpSession session) {
        AdminInfo adminInfo = (AdminInfo)session.getAttribute(LoginInterceptor.LONGIN_SESSION_NAME);
        if(dto.getUserid()!=null&&dto.getUserid()>0) { //update
            int count = commonJdbcUtils.queryObject("select count(1) from userinfo where openid=? and validflag='1' and userid<>?",
                    Integer.class,dto.getOpenid(),dto.getUserid());
            if(count>=1)
                throw new EyasBusinessException("该登录账号已存在有效的数据，");
            UserInfo userInfo1 = commonJdbcUtils.queryObject("select * from userinfo where userid=?",UserInfo.class,dto.getUserid());
            if(dto.getSex()!=null)
                userInfo1.setSex(dto.getSex());
            //排除sex和validflag、addtime，其他的字段进行更新
            BeanUtils.copyProperties(dto,userInfo1,"openid","sex","restclass","totleclass","totleamount","rechargenum",
                    "validflag","addtime","tiyannums","tiyansums","userstr");
            userInfo1.setAddid(dto.getAddid());
            userInfo1.setUpdateid(adminInfo.getAdminnid());
            userInfo1.setUpdatetime(new Date());
            commonJdbcUtils.update(userInfo1);

            //孩子信息
            if(dto.getChildren()!=null) {
                dto.getChildren().setUserid(userInfo1.getUserid());
                if(dto.getChildren().getCid()!=null&&dto.getChildren().getCid()!=0) {// update
                    commonJdbcUtils.update(dto.getChildren());
                }else {//insert
                    commonJdbcUtils.insert(dto.getChildren());
                }
            }

        }else {// insert
            int count = commonJdbcUtils.queryObject("select count(1) from userinfo where openid=? and validflag='1'",Integer.class,dto.getOpenid());
            if(count>=1)
                throw new EyasBusinessException("该登录账号已存在有效的数据，");
            UserInfo userInfo1 = new UserInfo();
            //排除sex和validflag、addid、addtime，其他的字段进行更新
            BeanUtils.copyProperties(dto,userInfo1,"sex","validflag","addid","addtime","tiyannums","tiyansums","userstr");
            if(dto.getSex()==null)
                userInfo1.setSex(1);
            else
                userInfo1.setSex(dto.getSex());
            userInfo1.setRestclass(0);
            userInfo1.setTotleclass(0);
            userInfo1.setTotleamount(0);
            userInfo1.setRechargenum(0);
            userInfo1.setValidflag("1");
            userInfo1.setAddtime(new Date());
            userInfo1.setTiyannums(0);
            userInfo1.setTiyansums(0);

            String userstr_no = commonJdbcUtils.queryObject("select nextval(?)",Integer.class,"seq_"+userStr.getSeqname())+"";
            String userstr = userStr.getSeqname();
            for(int i=0;i<5-userstr_no.length();i++) {
                userstr += "0";
            }
            userstr += userstr_no;
            userInfo1.setUserstr(userstr);

            if(adminInfo!=null){
                userInfo1.setAddid(adminInfo.getAdminnid());
            }
            commonJdbcUtils.insert(userInfo1);
            //孩子信息
            if(dto.getChildren()!=null) {
                dto.getChildren().setUserid(userInfo1.getUserid());
                if(dto.getChildren().getCid()!=null&&dto.getChildren().getCid()!=0) {// update
                    commonJdbcUtils.update(dto.getChildren());
                }else {//insert
                    commonJdbcUtils.insert(dto.getChildren());
                }
            }
        }

    }

    @Override
    public void changeClassFollow(QueryPageParmDTO dto) {
        int updaterows = commonJdbcUtils.update("update userandclass set validflag=? where userid=? and classid=?",dto.getValidflag(),dto.getUserid(),dto.getClassid());
        if(dto.getValidflag().equals("1")&&updaterows==0) {
            UserAndClass userAndClass = new UserAndClass();
            userAndClass.setUserid(dto.getUserid());
            userAndClass.setClassid(dto.getClassid());
            userAndClass.setValidflag("1");
            commonJdbcUtils.insert(userAndClass);
        }

    }
}
